package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.Shop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.security.PrivateKey;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;



@Slf4j
@Component
public class CacheClient {
    public final long CACHE_NULL_TTL = 2L;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    //将任意对象转换成json字符串后存储在redis中,可以设置过期时间
    public void set(String key, Object value, Long time, TimeUnit unit){

        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }
    //将任意对象封装成RedisData对象，然后转换成json字符串后存储在redis中,可以设置逻辑过期时间
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit){
        //设置逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        redisData.setData(value);
        //存入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    //利用空值解决缓存穿透
    public  <R, ID> R queryWithPassThrough(
            String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit){
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if(StrUtil.isNotBlank(json)){
            return JSONUtil.toBean(json, type);
        }
        //判断是否为空值（不为null，但是没有值）
        if(json != null){
            return null;
        }
        //利用函数式编程解决
        R r = dbFallback.apply(id);
        if(r == null){
            //将空值写入redis
            this.set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            //返回错误值
            return null;
        }
        //存在，存入redis
        this.set(key, r, time, unit);
        return r;

    }

    //利用逻辑过期时间解决缓存击穿
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    public <R, ID> R queryWithLogicalExpire(
            String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback, Long time, TimeUnit unit){

        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        //如果redis为空，直接返回null
        if(StrUtil.isBlank(json)){
            return null;
        }
        //当前redis中的店铺数据data
        // 先填充 RedisData 对象
        RedisData redisData = JSONUtil.toBean(json, RedisData.class);
        // 从 RedisData 对象中获取 Shop 数据
        R r = JSONUtil.toBean(redisData.getData().toString(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        //未过期，直接返回数据
        if(expireTime.isAfter(LocalDateTime.now())){
            return r;
        }

        //过期，缓存重建
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;

        try {
            //尝试获取锁
            boolean isLock = tryLock(lockKey);
            //没获取到锁
            if (! isLock) {
                //获取旧数据，返回
                return r;
            }
            //获取到锁后再次判断是否过期
            RedisData redisData1 = JSONUtil.toBean(stringRedisTemplate.opsForValue().get(key), RedisData.class);
            expireTime = redisData1.getExpireTime();
            if(expireTime.isAfter(LocalDateTime.now())){
                return JSONUtil.toBean(redisData1.getData().toString(), type);
            }
            //获取到锁,开启新线程，将要更新的信息发送到redis中
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                //设置逻辑过期时间后存入redis
                setWithLogicalExpire(key, dbFallback.apply(id), time, unit);
            });

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //释放锁
            unlock(lockKey);
        }
        //返回过期的店铺信息
        return r;

    }

    //获取互斥锁
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", RedisConstants.LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    //删除互斥锁
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

}
